package com.huaxin.common.view;

/**
 * Created by Administrator on 2017/1/13.
 */

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.InputType;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;

import com.huaxin.common.R;




public class VerifyCodeView extends View {
    private final int codeNumber;
    private final Paint paint;
    StringBuilder verifyCodeBuilder;
    //一个框占用的宽度
    private int rectWidth;

    //两字符间隔
    private int dividerSpace;
    private float textSize;
    Paint textPaint;
    int padding =10;

    public VerifyCodeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //能获取焦点才能弹出软键盘

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CodeView);
        codeNumber = typedArray.getInt(R.styleable.CodeView_codeNumber, 6);
        dividerSpace = typedArray.getDimensionPixelSize(R.styleable.CodeView_codeSpace, 20);
        rectWidth = typedArray.getDimensionPixelSize(R.styleable.CodeView_lengthSide, 50);
        textSize = typedArray.getDimensionPixelSize(R.styleable.CodeView_textSize, 20);
        typedArray.recycle();

        setFocusable(true);
        setFocusableInTouchMode(true);
        verifyCodeBuilder = new StringBuilder(codeNumber);
        textPaint=new TextPaint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setTextSize(textSize);
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setColor(Color.WHITE);
        textPaint.setTextAlign(Paint.Align.CENTER);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(4);

        setMinimumWidth(rectWidth*codeNumber+dividerSpace*(codeNumber-1) + 2*padding);
        setMinimumHeight(rectWidth+2*padding);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int width;
        int height;


        if (widthMode == MeasureSpec.EXACTLY) {
            // Parent has told us how big to be. So be it.
            width = widthSize;
        } else {
            width = codeNumber*rectWidth + dividerSpace*(codeNumber-1);
            width = Math.max(width, getSuggestedMinimumWidth());

            if (widthMode == MeasureSpec.AT_MOST) {
                width = Math.min(widthSize, width);
            }
        }

        if (heightMode == MeasureSpec.EXACTLY) {
            // Parent has told us how big to be. So be it.
            height = heightSize;

        } else {
            height = rectWidth;
            height = Math.max(height, getSuggestedMinimumHeight());

            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(heightSize, height);
            }
        }

        setMeasuredDimension(width, height);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //在View上点击时弹出软键盘
        if (isFocusable() && !isFocused()) {
            requestFocus();
        }
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.viewClicked(this);
        imm.showSoftInput(this, 0);
        Log.d("Zoes","touch!"+imm.isActive()+imm.isActive(this));
        return super.onTouchEvent(event);
    }
    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        //定义软键盘样式为数字键盘
        outAttrs.inputType = InputType.TYPE_CLASS_NUMBER;
        outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI;
        return super.onCreateInputConnection(outAttrs);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //接收按键事件，67是删除键(backspace),7-16就是0-9
        if (keyCode == KeyEvent.KEYCODE_DEL && verifyCodeBuilder.length() > 0) {
            verifyCodeBuilder.deleteCharAt(verifyCodeBuilder.length() - 1);
            //重新绘图
            invalidate();
        } else if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9 && verifyCodeBuilder.length() < 6) {
            verifyCodeBuilder.append(keyCode - 7);
            invalidate();
        }
        //到了6位自动隐藏软键盘
        if (verifyCodeBuilder.length() >= 6) {
            InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getWindowToken(), 0);
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 获取输入的验证码
     * @return
     */
    public String getVerifyCodeStr() {
        return verifyCodeBuilder.toString();
    }
    /**
     * 设置显示的验证码
     * @param verifyCode
     */
    public void setVerifyCode(String verifyCode) {
        if(verifyCodeBuilder.length()>0) {
            verifyCodeBuilder.delete(0, verifyCodeBuilder.length());
        }
        verifyCodeBuilder.append(verifyCode);
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);


        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();

        float left = padding;
        float top = padding;
        float right = left + rectWidth;
        float bottom = top + rectWidth;


        float textHeight,center,textBaseY;


        for(int i=0;i<codeNumber;i++){
            if(i<verifyCodeBuilder.length()){

                textHeight = fontMetrics.descent - fontMetrics.ascent;
                center = left + rectWidth /2;
                textBaseY = top + (rectWidth - textHeight)/2 - fontMetrics.ascent;
                canvas.drawText(getVerifyCodeStr().toCharArray(),i,1,center,textBaseY,textPaint);

                paint.setAlpha(255);
                canvas.drawRect(left,top,right,bottom,paint);
            }else{
                paint.setAlpha(176);
                canvas.drawRect(left,top,right,bottom,paint);
            }
            left = right + dividerSpace;
            right = left + rectWidth;
        }

    }

    @Override
    public boolean onCheckIsTextEditor() {
        return true;
    }
}